package com.maple.controller.admin;

import com.maple.enumeration.ExceptionEnum;
import com.maple.exception.BusinessException;
import com.maple.result.Result;
import com.maple.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
public class UploadController {

    @Autowired
    AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile file){
      log.info("文件上传：{}", file);
        try {
//      判断文件大小
            long size = file.getSize();
            if(size > 1024 * 1024 * 2){
                throw new BusinessException(ExceptionEnum.TOO_LARGE);
            }

//      获得原始的文件名
            String filename = file.getOriginalFilename();

//        获得文件的小写后缀名
            String last = filename.substring(filename.lastIndexOf(".")).toLowerCase();

//        判断文件类型
            if(last.contains(".jpg") && last.contains(".png") && last.contains(".jpeg")){
                throw new BusinessException(ExceptionEnum.TYPE_ERROR);
            }

//        生成一个唯一标识
            String newFileName = UUID.randomUUID() + filename;

//        使用工具类，获得文件路径
            String upload = aliOssUtil.upload(file.getBytes(), newFileName);

//        返回结果
            return Result.success(upload);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
